package com.example.foldertreeview;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.foldertreeview.fragments.CallPathFragment;
import com.example.foldertreeview.fragments.CallShowFragment;
import com.google.android.material.tabs.TabLayout;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String[] permissions = {
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    //tabLayout
    private TabLayout tabLayout;

    private Toolbar toolbar;
    private ImageButton backImageBtn;

    private String[] tabLayoutList = new String[]{"电话录音文件", "电话录音路径"};
    //viewPager
    private ViewPager viewPager;
    private List<Fragment> fragments = new ArrayList<>();

    private TextView brandView,sysVersionView,callRecordPathView;
    private AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPermissionAndData();
        bestPermissionX();
        //注册EventBus
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        initView();
        initPageViewer();
    }

    /**
     * 开通权限 Manifest.permission.READ_CONTACTS,
     *             Manifest.permission.READ_CALL_LOG,
     *             Manifest.permission.READ_EXTERNAL_STORAGE
     */
    private void bestPermissionX(){
        PermissionX.init(this)
                .permissions(
                        Manifest.permission.INTERNET,
                        Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_CALL_LOG

                )
                .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
                .onExplainRequestReason(
                        new ExplainReasonCallbackWithBeforeParam() {
                            @Override
                            public void onExplainReason(ExplainScope scope, List<String> deniedList, boolean beforeRequest) {
                                scope.showRequestReasonDialog(deniedList, "即将申请的权限是程序必须依赖的权限", "确定","取消");

                            }
                        }).request(new RequestCallback(){
            @Override
            public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                if (allGranted) {
                    Toast.makeText(MainActivity.this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "您拒绝了如下权限：" + deniedList, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //初始化权限和数据
    private void initPermissionAndData(){
        List<String> permissionList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ActivityCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permissions[i]);
            }
        }
        if (permissionList.size() <= 0) {
//            Toast.makeText(this,"已授权-1",Toast.LENGTH_LONG).show();
//            CallQueryAsyncTask task = new CallQueryAsyncTask(MainActivity.this,listView);
//            task.execute();
//            adapter = new CallRecordAdapter(this,PhoneCallUtils.getLast10CallDetails(this));
//            listView.setAdapter((ListAdapter) adapter);
        } else {
            //存在未允许的权限
            ActivityCompat.requestPermissions(this, permissions, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean haspermission = false;
        if (100 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    haspermission = true;
                }
            }
            if (haspermission) {
                //跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
                permissionDialog();
            } else {
//                Toast.makeText(this,"已授权-2",Toast.LENGTH_LONG).show();
//                CallQueryAsyncTask task = new CallQueryAsyncTask(MainActivity.this,listView);
//                task.execute();
//                adapter = new CallRecordAdapter(this,PhoneCallUtils.getLast10CallDetails(this));
//                listView.setAdapter((ListAdapter) adapter);
            }
        }
    }
    //打开手动设置应用权限
    private void permissionDialog() {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(this)
                    .setTitle("提示信息")
                    .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // cancelPermissionDialog();
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // cancelPermissionDialog();
                        }
                    })
                    .create();
        }
        alertDialog.show();
        alertDialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 接收信息
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        //接收消息改变按钮文字并打印信息
        if (event.getType() == MsgConstant.msg_type){
            Log.d("TAG", "receive： Message ===" +  event.getCount());
            callRecordPathView.setText(event.getMsg());
        }

    }

    private void initView(){
        //设置toolbar代替原有样式
        toolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        backImageBtn = findViewById(R.id.backBtn); //返回按钮

        brandView = findViewById(R.id.brandTxt);
        sysVersionView = findViewById(R.id.sysVersionTxt);
        callRecordPathView = findViewById(R.id.callRecordPathTxt);
        //手机品牌、系统版片
        brandView.setText(Build.BRAND);
        sysVersionView.setText(Build.DISPLAY);
        //录音路径：有默认，则按默认值，否则，取当前手机值
        if (SharedPreferencesUtils.getCallRecordPath(MainActivity.this)=="none"){
            callRecordPathView.setText(CallRecordPath.getFilePath());
        }else{
            callRecordPathView.setText(SharedPreferencesUtils.getCallRecordPath(MainActivity.this));
        }
    }

    private void initPageViewer(){
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewpager);
        for (int i = 0; i < tabLayoutList.length; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }
        //创建fragment，并添加到fragment数据源集合中
        CallShowFragment callFragment = new CallShowFragment();
        CallPathFragment pathFragment = new CallPathFragment();
        fragments.add(callFragment);
        fragments.add(pathFragment);
        //将fragment数据源集合放入ViewPager适配器中
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments, tabLayoutList);

        //给ViewPager设置适配器
        viewPager.setAdapter(viewPagerAdapter);

        //将tabLayout和ViewPager绑定，达到切换tab就切换ViewPager的效果
        tabLayout.setupWithViewPager(viewPager, false);
    }


}